<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\ListBuilder;
use app\common\service\UploadService;
use app\common\trait\SettingsTrait;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageAppointmentService;
use plugin\ycMassage\utils\enum\ServiceState;
use think\Request;

class AppointmentServiceController extends BaseController
{
    use SettingsTrait;

    /**
     * 应用ID（null则获取系统配置）
     * @var int|null
     * @author 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    protected $saas_appid = null;

    /**
     * 构造函数
     * @return void
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function initialize()
    {
        parent::initialize();
        $this->saas_appid = $this->request->saas_appid;
    }
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 100
        ]);
        $builder->addRightButton('endService', '结束服务', [
            'api'    => $this->pluginPrefix . '/admin/AppointmentService/endService',
            'type'      => 'confirm',
            'method' => 'delete',
            'params' => [
                'field' => 'state',
                'where' => 'in',
                'value' => [ServiceState::WAIT_START['value'], ServiceState::TRAVELING['value'], ServiceState::ARRIVAL['value'], ServiceState::ING['value']]
            ],
        ], [
            'type' => 'danger',
            'title'   => '温馨提示',
            'content' => '是否确认结束服务？如有加钟需要退款，请先引导用户申请退款在结束服务。',
        ], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addScreen('trade', 'input', '订单号');
        $builder->addScreen('name', 'input', '下单人');
        $builder->addScreen('mobile', 'input', '下单手机号');
        $builder->addScreen('technician', 'input', '技师');
        $builder->addScreen('state', 'select', '状态', [
            'options' => ServiceState::getOptions()
        ]);
        $builder->addScreen('start_time', 'input', '开始时间', [
            'type' => 'date'
        ]);
        $builder->addScreen('end_time', 'input', '结束时间', [
            'type' => 'date'
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90
        ])
            ->addColumn('title', '服务项目', [
                'minWidth' => 200,
            ])
            ->addColumn('uid', 'UID', [
                'width' => 100,
            ])
            ->addColumn('name', '下单人', [
                'width' => 160,
            ])
            ->addColumn('mobile', '下单手机号', [
                'width' => 160,
            ])
            ->addColumn('technician_id', '技师UID', [
                'width' => 100,
            ])
            ->addColumnEle('technician_headimg', '技师', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('technician_nickname', '技师', [
                'width' => 160,
            ])
            ->addColumn('trade', '订单号', [
                'minWidth' => 200,
            ])
            ->addColumnEle('state', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => ServiceState::dictOptions(),
                    'style' => ServiceState::dictOptions('style'),
                ],
            ])
            ->addColumn('start_time', '预约服务时间', [
                'width' => 200,
            ])
            ->addColumn('commuting_duration', '计划通勤时长(分钟)', [
                'width' => 160,
            ])
            ->addColumn('departure_time', '出发时间', [
                'width' => 200,
            ])
            ->addColumn('arrival_time', '到达时间', [
                'width' => 200,
            ])
            ->addColumnEle('arrival_photo', '到达照片', [
                'width' => 80,
                'params' => [
                    'type' => 'image',
                    'props'=>[
                        'preview'=>true
                    ]
                ],
            ])
            ->addColumn('commuting_time', '实际通勤时长', [
                'width' => 160,
            ])
            ->addColumnEle('verification', '核验', [
                'width' => 100,
                'params' => [
                    'type' => 'tags',
                    'options' => [
                        0 => '未核验',
                        1 => '已核验'
                    ],
                    'style' => [
                        0=>[
                            'type' => 'info'
                        ],
                        1=>[
                            'type' => 'success'
                        ]
                    ],
                ],
            ])
            ->addColumn('verification_time', '核验时间', [
                'width' => 200,
            ])
            ->addColumn('duration', '服务时长(分钟)', [
                'width' => 160,
            ])
            ->addColumn('service_start_time', '服务开始时间', [
                'width' => 200,
            ])
            ->addColumnEle('service_start_photo', '开始照片', [
                'width' => 80,
                'params' => [
                    'type' => 'image',
                    'props'=>[
                        'preview'=>true
                    ]
                ],
            ])
            ->addColumn('service_end_time', '服务结束时间', [
                'width' => 200,
            ])
            ->addColumnEle('service_end_photo', '结束照片', [
                'width' => 80,
                'params' => [
                    'type' => 'image',
                    'props'=>[
                        'preview'=>true
                    ]
                ],
            ])
            ->addColumn('service_duration_time', '实际服务时长', [
                'width' => 160,
            ])
            ->addColumn('remark', '备注', [
                'width' => 160,
            ])
            ->addColumn('create_time', '下单时间', [
                'width' => 160,
            ]);
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['a.saas_appid', '=', $request->saas_appid]
        ];
        $trade = $request->get('trade');
        if ($trade) {
            $where[] = ['o.trade', '=', $trade];
        }
        $uid = $request->get('uid');
        if ($uid) {
            $where[] = ['a.uid', '=', $uid];
        }
        $state = $request->get('state');
        if ($state !== null) {
            $where[] = ['a.state', '=', $state];
        }
        $start_time = $request->get('start_time');
        if ($start_time) {
            $where[] = ['a.start_time', '>=', $start_time . ' 00:00:00'];
        }
        $end_time = $request->get('end_time');
        if ($end_time) {
            $where[] = ['a.start_time', '<=', $end_time . ' 23:59:59'];
        }
        $type = $request->get('type');
        if ($type) {
            $where[] = ['a.orders_type', '=', $type];
        }
        $filed = [
            'a.*',
            'o.trade,o.remark',
            's.title'
        ];
        $MassageOrdersObj = MassageAppointmentService::alias('a')->where($where);
        $MassageOrdersObj->join('MassageOrders o', 'o.id=a.orders_id');
        $filed[] = 'address.name,address.mobile';
        $filed[] = 'ut.nickname as technician_nickname,ut.headimg as technician_headimg';
        $technician = $request->get('technician');
        if ($technician) {
            $where[] = ['t.name|t.mobile', 'like', "%{$technician}%"];
        }
        $MassageOrdersObj->join('MassageUserTechnician t', 't.uid=a.technician_id');
        $MassageOrdersObj->join('MassageUser ut', 'ut.id=a.technician_id');
        $name = $request->get('name');
        if ($name) {
            $where[] = ['address.name', 'like', "%{$name}%"];
        }
        $mobile = $request->get('mobile');
        if ($mobile) {
            $where[] = ['address.mobile', 'like', "%{$mobile}%"];
        }
        $MassageOrdersObj->join('MassageOrdersAddress address', 'address.orders_id = a.orders_id');
        $MassageOrdersObj->join('MassageService s', 's.id = a.service_id');
        $data = $MassageOrdersObj->order('a.id desc')
            ->field($filed)
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                if ($item->technician_nickname) {
                    $item->technician_nickname = base64_decode($item->technician_nickname);
                }
                if (strpos($item->technician_headimg, 'http') !== 0) {
                    $item->technician_headimg = UploadService::url($item->technician_headimg);
                }
                $commuting_time='';
                if($item->departure_time && $item->arrival_time){
                    $commuting_time = MassageGetTimeText(strtotime($item->arrival_time) - strtotime($item->departure_time));
                }
                $item->commuting_time = $commuting_time;
                $service_duration_time='';
                if($item->service_start_time && $item->service_end_time){
                    $service_duration_time = MassageGetTimeText(strtotime($item->service_end_time) - strtotime($item->service_start_time));
                }
                $item->service_duration_time = $service_duration_time;
            });
        return $this->successRes($data);
    }
    public function endService(Request $request)
    {
        $id = $request->post('id');
        $model=MassageAppointmentService::where(['id'=>$id,'saas_appid'=>$request->saas_appid])->find();
        if(!$model){
            return $this->fail('数据不存在');
        }
        if(!in_array($model->state,[ServiceState::WAIT_START['value'], ServiceState::TRAVELING['value'], ServiceState::ARRIVAL['value'], ServiceState::ING['value']])){
            return $this->fail('当前状态不允许结束服务');
        }
        $date=date('Y-m-d H:i:s');
        if(!$model->departure_time){
            $model->departure_time=$date;
        }
        if(!$model->arrival_time){
            $model->arrival_time=$date;
        }
        if(!$model->service_start_time){
            $model->service_start_time=$date;
        }
        if(!$model->verification){
            $model->verification=1;
            $model->verification_time=$date;
        }
        $model->state = ServiceState::ING['value'];
        $model->save();
        try {
            $options = new \stdClass();
            $options->id = $model->id;
            $options->saas_appid = $model->saas_appid;
            $options->action = 'technician';
            $options->uid = $model->technician_id;
            $options->latitude = null;
            $options->longitude = null;
            MassageAppointmentService::endService($options);
        } catch (\Throwable $th) {
            return $this->fail($th->getMessage());
        }

        return $this->success('操作成功');
    }
}
